<template>
  <el-card>
    <div slot="header">
      <el-row type="flex" justify="space-between">
        <h4>销售属性</h4>
        <!-- 按钮操作栏 -->
        <BtnRender :render="renderBtnsBar" />
      </el-row>
    </div>
    <div>
      <div
        v-for="(spec, index) in specList"
        :key="(spec.attributeUuid + index)"
        class="spec_item_wrap"
      >
        <el-row type="flex" justify="space-between" align="middle" class="spec_title_wrap">
          <h4 class="blue_color">{{ spec.attributeName }}：</h4>
          <el-button
            icon="el-icon-plus"
            type="text"
            @click="handleAddCustomSpec({ key: spec.attributeName })"
          >添加规格值</el-button>
        </el-row>
        <el-checkbox-group
          v-model="saleAttrList[spec.attributeName]"
          @change="list => { handleChooseSpec({ list, key: spec.attributeName }) }">
          <el-checkbox
            v-for="(item, index) in spec.values"
            :key="(item.valueUuid + index)"
            :label="item.valueUuid || item.valueName"
            :disabled="item.isUsable == false"
          >
            <template v-if="item.officialFlag === 'Y'">{{ item.valueName }}</template>
            <template v-else>
              {{ item.valueName }}
              <el-button
                type="text"
                icon="el-icon-delete-solid"
                @click="handleRemoveCustomSpec({ key: spec.attributeName, valueName: item.valueName })"
              />
            </template>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <BasicTable
        v-if="attributesSkuList.length > 0"
        :showPagination="false"
        :showSelectCol="false"
        :data-source="attributesSkuList"
        :columns="attributesSkuColumns"
        :loading="attributesSkuLoading"
      />
    </div>
    <BasicDialog
      title="规格名称"
      width="50%"
      :visible.sync="addCustomSpec.visible"
      :handleClose="handleCancel"
    >
      <el-input
        v-model="addCustomSpec.input"
        placeholder="请填写自定义规格名称"
        type="textarea"
        :autosize="{minRows: 5,maxRows: 15}"
      ></el-input>
      <el-row slot="ft" style="text-align: center">
        <el-button type="primary" @click="handleOK">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-row>
    </BasicDialog>
    <SelectProductDialog
      :visible.sync="tempDialog.visible"
      @getSelectResults="getSelectTempGoods"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicDialog from '@/components/BasicDialog';
import descartes from '@/assets/js/dikaerji';
import { judgeIsRepeatFunc, createExcelByExport, generateUuid } from '@/utils/bizUtils';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { exportSaleAttrTemplateService, queryTemporaryGoodsService } from '@/api/commodity/common';
import BasicTable from '@/components/BasicTable';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SelectProductDialog from '@/pages/commodity/components/SelectProductDialog';
export default {
  components: {
    BasicDialog,
    BtnRender,
    BasicTable,
    RemoteSelect,
    SelectProductDialog
  },
  props: {
    specList: {
      type: Array,
      default () {
        return [];
      }
    },
    isGenerateCode: {
      type: Boolean,
      default: false
    },
    categoryUuid: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      hasSelectSpecIdList: [],
      addCustomSpec: {
        visible: false,
        input: '',
        key: ''
      },
      saleAttrList: {}, // 规格属性的类型集合，给每一个赋值空数组，以供checkbox的v-model双向绑定
      resetSpecList: {}, // 重新组装结构后的specList
      mappingSpecList: {}, // 选择checkbox时，存储对应的对象集合
      // dikaerKeysList: new Set(), // 当前已选的规格属性类别集合
      attributesSkuList: [], // 规格属性表格数据
      attributesSkuColumns: [],
      attributesSkuLoading: false,
      dikaerNewList: [],
      skuList: [],
      exportBtnLoading: false, // 导出按钮loading
      tempDialog: {
        visible: false,
        currentIndex: null
      }
    }
  },
  watch: {
    specList: {
      handler (val) {
        this.init()
      },
      immediate: true
    }
  },
  computed: {
    hasImportData () {
      return this.skuList.length !== 0;
    }
  },
  methods: {
    // descartes,
    init () {
      this.saleAttrList = this.specList.reduce((value, item) => {
        value[item.attributeName] = [];
        this.resetSpecList[item.attributeName] = item;
        return value;
      }, {});
      this.dikaerNewList = [];
      this.attributesSkuList = [];
      this.setTableColumns();
    },
    handleGenerateCode () {
      const attributesSkuList = this.attributesSkuList.filter(item => item.isSelect)
      if (attributesSkuList.length === 0) {
        return this.$message.warning('生成SKU编码数据为空')
      }
      let getSellWellFlag = val => ({ sellWellFlag: val ? '1' : '2' }) // 1为畅销；2为非畅销
      let getImportSkuList = () => {
        const skuList = this.skuList.map((item, index) => {
          const { skuNo, isSelect, sellWellFlag, barcode, enumTempProduct } = this.attributesSkuList[index]
          if (isSelect) return { ...item, skuNo, ...getSellWellFlag(sellWellFlag), barcode, enumTempProduct }
        }).filter(item => item)
        return skuList
      }
      let getDikaerSkuList = () => {
        const skuList = this.dikaerNewList.map((item, index) => {
          const { skuNo = null, isSelect, sellWellFlag, barcode, enumTempProduct } = this.attributesSkuList[index]
          console.log(this.attributesSkuList[index]);
          if (isSelect) return { skuNo, specList: item, ...getSellWellFlag(sellWellFlag), barcode, enumTempProduct }
        }).filter(item => item);
        return skuList
      }
      const data = {
        skuList: this.hasImportData ? getImportSkuList() : getDikaerSkuList(),
        attributesSkuList
      }
      this.$emit('generateSkuList', data);
      getImportSkuList = null
      getDikaerSkuList = null
    },
    /* 生成助记码接口调用 */
    generateHelpCodeAction (params) {
      let loadingInstance = this.$loading({
        target: '.form_body_wrap',
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        fullscreen: false
      });
      return new Promise((resolve, reject) => {
        ApiRequest(
          '/sysback/addsingleproduct/basicinfo/getHelpCodeMultipart',
          'post',
          params
        ).then(res => {
          loadingInstance.close();
          if (res.retStatus !== '1') {
            resolve(false);
            return false;
          }
          resolve(res.retData)
        })
      })
    },
    handleOK () {
      if (!this.addCustomSpec.input) {
        return this.$message.warning('请填写内容');
      }
      const skuInfoList = this.addCustomSpec.input.split(/\n/).map(item => item.trim());
      // const skuInfoList = this.addCustomSpec.input.replace(/[ ]/g, '').split(/\n/).filter(item => item);
      const MAX_ROW_NUM = 100; // 最大提交行数
      const LIMIT_LENGTH = 30; // 规格值每行最大长度限制
      if (skuInfoList.length > MAX_ROW_NUM) {
        return this.$message.warning(`超过最大${MAX_ROW_NUM}行限制`);
      }
      const overLengthFlag = skuInfoList.some(item => item.length > LIMIT_LENGTH);
      if (overLengthFlag) {
        return this.$message.warning(`有规格超出${LIMIT_LENGTH}限制`);
      }
      const intersectTarget = judgeIsRepeatFunc(
        this.resetSpecList[this.addCustomSpec.key].values,
        skuInfoList,
        'valueName'
      );
      if (intersectTarget.length !== 0) {
        return this.$message.warning('有规格名称已被占用');
      }
      const uniqSkuInfoList = [...new Set(skuInfoList)];
      this.generateHelpCodeAction(uniqSkuInfoList).then(res => {
        if (!res) { return false; }
        res.forEach(item => {
          this.resetSpecList[this.addCustomSpec.key].values.push({
            helpCode: item.helpCodeVo?.helpCode,
            valueName: item.chineseName,
            valueUuid: '',
            officialFlag: 'N',
            selected: false,
            attributeUuid: this.resetSpecList[this.addCustomSpec.key].attributeUuid,
            attributeName: this.resetSpecList[this.addCustomSpec.key].attributeName
          });
        })
        this.getSpecTableDataFn();
        this.addCustomSpec.input = '';
        this.addCustomSpec.visible = false;
      })
    },
    handleCancel () {
      this.addCustomSpec.visible = false;
    },
    handleRemoveCustomSpec (data) {
      let { key, valueName } = data;
      let index = _.findIndex(this.resetSpecList[key].values, item => {
        return item.valueName === valueName;
      })
      if (index === -1) {
        return false;
      }
      this.resetSpecList[key].values.splice(index, 1);
      this.handleChooseSpec({ list: this.hasSelectSpecIdList, key })
    },
    handleAddCustomSpec (data) {
      let { key } = data;
      this.addCustomSpec.key = key;
      this.addCustomSpec.visible = true;
    },
    // 选择是否畅销
    handleSelectSellFlag (data) {
      const { val, index } = data
      // 是否畅销 1:是 2:否
      this.dikaerNewList[index].sellWellFlag = val
    },
    handleCancelSelect (data) {
      let { val, index } = data;
      this.dikaerNewList[index].isSelect = val;
    },
    handleChooseSpec (data) {
      let { list, key } = data;
      this.hasSelectSpecIdList = list;
      // this.dikaerKeysList.add(key);
      this.mappingSpecList[key] = list.reduce((value, uuid) => {
        let target = _.find(this.resetSpecList[key].values, spec => {
          return (spec.valueUuid || spec.valueName) === uuid;
        })
        if (target) {
          target.attributeUuid = this.resetSpecList[key].attributeUuid;
          target.attributeName = this.resetSpecList[key].attributeName;
          target.selected = true;
          value.push(target);
        }
        return value;
      }, []);
      this.getSpecTableDataFn();
    },
    /* 获取组装笛卡尔积的数据 */
    assembleDescartesFn () {
      // let specKeysList = [...this.dikaerKeysList];
      const specKeysList = this.specList.map(item => item.attributeName)
      let descartesList = [];
      specKeysList.forEach(key => {
        // if (this.mappingSpecList[key].length === 0) { return false }
        if (!this.mappingSpecList[key] || this.mappingSpecList[key].length === 0) { return false }
        descartesList.push(this.mappingSpecList[key]);
      })
      return descartes(descartesList);
    },
    /* 获取规格属性表格数据 */
    getSpecTableDataFn () {
      this.dikaerNewList = this.assembleDescartesFn();
      this.dikaerNewList.forEach((item) => {
        item.isSelect = true;
      })
      this.attributesSkuList = this.dikaerNewList.reduce((value, item) => {
        let valueNameList = [];
        let helpCodeList = [];
        item.forEach(spec => {
          valueNameList.push(spec.valueName);
          helpCodeList.push(spec.helpCode);
        })
        if (valueNameList.length === 0 && helpCodeList.length === 0) {
          return value;
        }
        value.push({
          valueName: valueNameList.join('/'),
          helpCode: helpCodeList.join('/'),
          isSelect: true
        })
        return value;
      }, []);
    },
    renderBtnsBar (h) {
      const size = 'mini';
      const btnsBar = [
        {
          label: '模板导出',
          method: this.handleExportTemplate,
          loading: this.exportBtnLoading,
          size
        },
        {
          label: '模板导入',
          action: 'sysback/product/addSku/basicInfo/importSkuDetail',
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: state => { this.attributesSkuLoading = state },
          size,
          data: { categoryUuid: this.categoryUuid }
        },
        {
          label: '生成SKU编码',
          method: this.handleGenerateCode,
          size
        }
      ];
      return getBtnsBar(h, btnsBar);
    },
    // 模板导出
    handleExportTemplate () {
      this.exportTemplate();
    },
    // 模板导入成功
    handleUploadSuccess (res) {
      if (res) {
        for (const key in this.saleAttrList) {
          this.saleAttrList[key] = [];
        }
        this.skuList = [];
        this.attributesSkuList = res.retData.map(item => {
          const { skuNo, productName, specList } = item;
          const row = {
            valueName: item.specModel,
            helpCode: item.specModelHelpCode,
            skuNo,
            productName,
            specModel: item.tempSpecModel,
            unitName: item.unitName,
            isSelect: true,
            sellWellFlag: false, // 导入默认非畅销
            enumTempProduct: item.enumTempProduct,
            enumTempProductName: item.enumTempProductName
          }
          this.skuList.push({ skuNo, specList });
          return row;
        });
      }
    },
    // 导出模板
    async exportTemplate () {
      const loadingFn = state => { this.exportBtnLoading = state };
      const data = { categoryUuid: this.categoryUuid };
      const res = await exportSaleAttrTemplateService(data, loadingFn);
      createExcelByExport({ res, excelTitle: '销售属性模板' + '_' + generateUuid() });
    },
    // 临采商品查询
    async getTemporaryGoodsList (skuNo) {
      const data = {
        nowPage: 1,
        pageShow: 10,
        searchParam: JSON.stringify([
          { name: 'skuNo', value: skuNo },
          { name: 'skuNo_q', value: 'EQ' }
        ])
      }
      const res = await queryTemporaryGoodsService(data);
      if (res?.retData.results) return res.retData?.results ?? [];
      return [];
    },
    // 设置获取选择的临采商品信息
    getSelectGoods (data, index) {
      this.setTempGoodsInfo(data, index);
    },
    // 点击选择临采商品弹框
    handleClickSelectTemp (index) {
      this.tempDialog.visible = true;
      console.log(index)
      this.tempDialog.currentIndex = index;
    },
    // 获取选择的临采商品
    getSelectTempGoods (data) {
      const index = this.tempDialog.currentIndex;
      this.setTempGoodsInfo(data, index);
    },
    // 设置临采商品信息
    setTempGoodsInfo (data, index) {
      this.$set(this.attributesSkuList[index], 'skuNo', data.skuNo)
      this.$set(this.attributesSkuList[index], 'productName', data.productName)
      this.$set(this.attributesSkuList[index], 'unitName', data.unitName)
      this.$set(this.tableInfo.list[index], 'specModel', data.specDetail)
      this.$set(this.tableInfo.list[index], 'enumTempProduct', data.enumTempProduct)
      this.$set(this.tableInfo.list[index], 'enumTempProductName', data.enumTempProductName)
    },
    // 设置表列
    setTableColumns () {
      const columns = [
        { title: '规格属性', key: 'valueName' },
        { title: '规格属性助记码', key: 'helpCode' },
        { title: '商品条形码',  key: 'barcode',  render: (h, { row, index }) => {
            return < el-input
              v-model={ row.barcode }
              disabled={ this.isGenerateCode }
            />
          }
        },
        {
          title: '商品编码',
          width: 150,
          render: (h, { row, index }) => {
            return <RemoteSelect
              placeholder="请选择商品编码"
              optionKeys={['skuNo', 'skuNo']}
              echoValue={row.skuNo}
              echoOptions={[row.skuNo, row.skuNo]}
              remoteSelectOptions={this.getTemporaryGoodsList}
              handleClickButton={() => { this.handleClickSelectTemp(index) }}
              onGetSelect={ data => { this.getSelectGoods(data, index) } }
            />
          }
        },
        { title: '商品大类', key: 'enumTempProductName' },
        { title: '商品名称', key: 'productName' },
        { title: '商品规格', key: 'specModel' },
        { title: '计量单位', key: 'unitName' },
        {
          title: '是否畅销',
          render: (h, { row, index }) => {
            return <el-checkbox
              v-model={ row.sellWellFlag }
              onChange={(val) => { this.handleSelectSellFlag({ val, index }) }}
              disabled={ this.isGenerateCode }
            />
          }
        },
        {
          title: '是否生成代码',
          render: (h, { row, index }) => {
            return <el-checkbox
              v-model={ row.isSelect }
              onChange={(val) => { this.handleCancelSelect({ val, index }) }}
              disabled={ this.isGenerateCode }
            />
          }
        }
      ]
      this.attributesSkuColumns = _.cloneDeep(columns);
    }
  }
}
</script>
<style lang="less" scoped>
.generate-cade-btn {
  float: right;
  padding: 3px 0;
}
/deep/ .spec_item_wrap {
  margin: 10px 0px;
  border-bottom: 1px solid #ccc;
  .spec_title_wrap {
    padding-bottom: 10px;
    border-bottom: 1px dashed #ccc;
  }
  .el-checkbox-group {
    min-height: 40px;
    line-height: 40px;
  }
  .blue_color {
    color: #5a9cf8;
  }
}
</style>
